const axios = require('axios');
const { db } = require('../db');
const { getRedisValue, setRedisValue } = require('../db/redis')
const cos = require('../service/tencos');
const { DYAPPID, DYAPPSECRET, DYAIAPPID, DYAIAPPSECRET } = require('../config');
const { access } = require('fs');
const { uploadFile } = require('../utils/uploadfile');
// const { getUserById, getUserByEmail, setValueByUserId } = require('../db/usermodel');
const { insertUserByOpenId, getUserById, getUserByOpenId, setValueByUserId } = require('../db/dyusermodel');
const { resultsWithCamelCase } = require('../utils/common');

// 登录相关
const accessTokenUrl = 'https://developer.toutiao.com/api/apps/v2/token'; // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/interface-request-credential/get-access-token
const jscode2Session = 'https://developer.toutiao.com/api/apps/v2/jscode2session'; // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/log-in/code-2-session

// 内容安全相关
const checkContentUrl = 'https://developer.toutiao.com/api/v2/tags/text/antidirt'; // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/content-security/content-security-detect

// 获取抖音小程序码
const dycodeUrl = 'https://developer.toutiao.com/api/apps/qrcode'; // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/url-and-qrcode/qrcode/create-qrcode

const dyCustomerService = 'https://developer.toutiao.com/api/apps/chat/customer_service_url'; // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/im/customer-service-url

const applets = {
    // MasterH超清壁纸
    [`${DYAPPID}`]: DYAPPSECRET,
    // MasterAI文案助手
    [`${DYAIAPPID}`]: DYAIAPPSECRET
}

axios.interceptors.request.use(config => {
    return config;
}, err => {

})

axios.interceptors.response.use(config => {
    return config;
}, (err) => {

})

/**
 * 获取小程序的access_token
 */
const getAccessToken = async (appid) => {
    let accessToken = await getRedisValue(appid);
    if (accessToken && accessToken != '') {
        return accessToken;
    }
    accessToken = await new Promise((resolve, reject) => 
        axios.post(accessTokenUrl, {
            grant_type: 'client_credential',
            appid: appid,
            secret: applets[appid]
        }).then((res) => {
            const dataObj = res.data;
            if (dataObj.err_no == 0) {
                setRedisValue(appid, dataObj.data.access_token, 7100);
                resolve(dataObj.data.access_token);
            } else {
                resolve({
                    status: dataObj.err_no,
                    msg: dataObj.err_tips
                });
            }
        }).catch((err) => {
            resolve(-1);
        })
    );
    return accessToken;
}

exports.getUserInfo = async (req, res) => {
    if (req.query.openid) {
        const dbUserInfo = await getUserByOpenId(req.query.openid);
        if (dbUserInfo) {
            return res.send({
                code: 200,
                msg: 'success',
                data: resultsWithCamelCase(dbUserInfo)
            });
        }
    }
    const result = await new Promise((resolve, reject) => {
        axios.post(jscode2Session, {
            appid: req.query.appid,
            secret: applets[req.query.appid],
            code: req.query.code
        }).then(res2 => {
            if (res2.status == 200) {
                const realRes = res2.data;
                if (realRes.err_no == 0) {
                    resolve(storeUserInfo2DB(realRes.data));
                } else {
                    return res.send({
                        code: realRes.err_no,
                        msg: realRes.err_tips
                    });
                }
            } else {
                return res.send({
                    code: res2.status,
                    msg: res2.statusText
                });
            }
        });
    });
    return res.send({
        code: 200,
        msg: 'success',
        data: result
    })
}

const storeUserInfo2DB = async (userInfo) => {
    // 先查询有没有数据
    const dbData = await getUserByOpenId(userInfo.openid);
    if (dbData) {
        return dbData;
    }
    const res = await insertUserByOpenId(userInfo.openid);
    if (res) {
        const data = await getUserByOpenId(userInfo.openid);
        return data;
    }
}

exports.checkContentSecurity = async (req, res) => {
    const accessToken = await getAccessToken(req.query.appid);
    if (accessToken.status) {
        return res.send(accessToken);
    }
    const result = await new Promise((resolve, reject) => {
        axios.post(checkContentUrl, {
            tasks: [{
                content: req.body.content
            }]
        }, {
            headers: {
                'X-Token': accessToken
            }
        }).then(res2 => {
            if (res2.status == 200) {
                const realRes = res2.data;
                if (realRes.log_id) {
                    // 正常返回
                    const predict = realRes.data[0].predicts[0];
                    resolve(predict.hit);
                } else {
                    return res.send({
                        code: realRes.code,
                        msg: realRes.message,
                        exception: realRes.exception
                    });
                }
            } else {
                return res.send({
                    code: res2.status,
                    msg: res2.statusText
                });
            }
        }).catch((err) => {
            return res.send({
                code: 500,
                msg: err.message
            });
        });
    });
    return res.send({
        code: 200,
        msg: 'success',
        data: {
            hit: result
        }
    });
}

exports.getDYcodeUrl = async (req, res) => {
    let accessToken = await getAccessToken(req.query.appid);
    const userInfo = await getUserByEmail('18656040185@163.com');
    if (userInfo.dycodeUrl) {
        return res.send({
            code: 200,
            msg: 'success',
            data: {
                url: userInfo.dycodeUrl
            }
        });
    }
    const userId = userInfo.id;
    const imageUrl = await new Promise((resolve, reject) => {
        axios.post(dycodeUrl, {
            access_token: accessToken,
            appname: 'douyin',
            is_circle_code: true,
        }, {
            responseType: 'arraybuffer'
        }).then(async res => {
            // 图片buffer 怎么处理
            if (res.status == 200) {
                const url = await uploadFile(userId, res.data, 'dycode');
                setValueByUserId(userId, 'dycodeUrl', url);
                resolve(url); // 图片buffer
            } else {
                return res.send({
                    status: res.status,
                    msg: res.statusText
                });
            }
        }).catch(err => {
            return res.send({
                status: 500,
                msg: JSON.stringify(err)
            });
        })
    });
    return res.send({
        code: 200,
        msg: 'success',
        data: {
            url: imageUrl
        }
    });
}

exports.addCount = async (req, res) => {
    const originData = await getUserById(req.body.id);
    if (originData) {
        const isSuccess = await setValueByUserId(req.body.id, {
            'can_use_count': originData.canUseCount + 5,
            'all_count': originData.allCount + 5
        });
        if (isSuccess) {
            return res.send({
                code: 200,
                msg: 'success'
            });
        } else {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后重试'
            });
        }
    } else {
        return res.send({
            code: 500,
            msg: '发生未知错误，请稍后重试'
        });
    }
}

exports.subCount = async (req, res) => {
    const originData = await getUserById(req.body.id);
    if (originData) {
        if (originData.canUseCount <= 0) {
            return res.send({
                code: 400,
                msg: '次数用完了'
            });
        }
        const isSuccess = await setValueByUserId(req.body.id, {
            'can_use_count': originData.canUseCount - 1
        });
        if (isSuccess) {
            return res.send({
                code: 200,
                msg: 'success'
            });
        } else {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后重试'
            });
        }
    } else {
        return res.send({
            code: 500,
            msg: '发生未知错误，请稍后重试'
        });
    }
}